package com.fqcar.fqdf.core.base;


import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.fqcar.fqdf.R;
import com.fqcar.fqdf.core.BaseRequestActivity;
import com.fqcar.fqdf.util.Constants;
import com.fqcar.fqdf.util.StorageUtil;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.fqdf.framework.android.util.CheckLogicUtil;
import com.fqdf.framework.android.util.DialogUtil;

import java.io.File;

/**
 * Created by lvsidong on 2017/1/10.
 */

public abstract class BasePhotoActivity extends BaseRequestActivity implements TakePhoto.TakeResultListener, InvokeListener {
    public TakePhoto takePhoto;
    private InvokeParam invokeParam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        configCompress(takePhoto);
//        configTakePhotoOption(takePhoto);
        return takePhoto;
    }

    @Override
    public void takeFail(TResult result, String msg) {
        DialogUtil.ToastMessage(this, msg);
    }

    @Override
    public void takeCancel() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    /**
     * 压缩
     *
     * @param takePhoto
     */
    public void configCompress(TakePhoto takePhoto) {

        takePhoto.onEnableCompress(getCompress(), false);
    }

    /**
     * 获取压缩设置
     *
     * @return
     */
    public CompressConfig getCompress() {
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(Constants.maxSize)
                .enableReserveRaw(false)
                .create();
        return config;
    }

    /**
     * 纠正拍照的照片旋转角度
     *
     * @param takePhoto
     */
    public void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    public CropOptions getCropOptions() {

        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(Constants.ImageSize.WIDTH).setAspectY(Constants.ImageSize.HEIGHT);
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    /**
     * 生成一个保存拍照文件的file
     *
     * @return file地址
     */
    protected File getGenerateFile() {
        File cache = StorageUtil.getTakePhotoDir(this);
        return new File(cache, StorageUtil.generateFileName());
    }

    /**
     * 开启照相
     *
     * @param path 存放图片的路径
     */
    public void takePhoto(File path) {
        if (path != null) {
            if (!path.getParentFile().exists()) {
                path.getParentFile().mkdirs();
            }
            getTakePhoto().onPickFromCapture(Uri.fromFile(path));
        }
    }

    /**
     * 拍照并裁切
     *
     * @param path
     * @param cropOptions
     */
    public void takePhotoWithCrop(File path, CropOptions cropOptions) {
        if (path != null) {
            if (!path.getParentFile().exists()) {
                path.getParentFile().mkdirs();
            }
            getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(path), cropOptions == null ? getCropOptions() : cropOptions);
        }
    }

    /**
     * 拍照并裁切
     *
     * @param path
     */
    public void takePhotoWithCrop(File path) {
        takePhotoWithCrop(path, null);
    }

    /**
     * 开启照相
     *
     * @param path 存放图片的路径
     */
    public void takePhoto(String path) {
        if (!CheckLogicUtil.isEmpty(path)) {
            takePhoto(new File(path));
        }
    }

    /**
     * 从当前图片库中选择一张图片
     */
    public void chosePhotoFromGallery() {
        getTakePhoto().onPickFromGallery();
    }

    /**
     * 从当前图片库中选择一张图片并剪切压缩
     *
     * @param outPath 压缩后图片保存的位置
     */
    public void chosePhotoFromGalleryWithCrop(File outPath) {
        chosePhotoFromGalleryWithCrop(outPath, null);
    }

    /**
     * 从当前图片库中选择一张图片并剪切压缩
     *
     * @param outPath 压缩后图片保存的位置
     * @param options 压缩参数
     */
    public void chosePhotoFromGalleryWithCrop(File outPath, CropOptions options) {
        if (outPath != null) {
            if (!outPath.getParentFile().exists()) {
                outPath.getParentFile().mkdirs();
            }
            getTakePhoto().onPickFromGalleryWithCrop(Uri.fromFile(outPath), options == null ? getCropOptions() : options);
        }
    }


    public interface PickAndCameraListener {
        void onClickTakePhoto();

        void selectPhotoFromGallery();
    }

    /**
     * 选择图片或者拍照获取图片的dialog
     */
    public class PickAndCameraPhotoDialog extends Dialog {
        private LinearLayout head_picture_from_album, head_picture_from_take_photo;
        private FrameLayout cancle_upload_head_picture;
        private PickAndCameraListener mListener;
        private MyTrueDismissListener mDismissListener;

        public PickAndCameraPhotoDialog(Context context) {
            super(context, R.style.car_belong_city_dialog_style);
        }

        public PickAndCameraPhotoDialog(Context context, PickAndCameraListener listener) {
            super(context, R.style.car_belong_city_dialog_style);
            mListener = listener;
        }

        public PickAndCameraPhotoDialog(Context context, PickAndCameraListener listener, MyTrueDismissListener dismissListener) {
            super(context, R.style.car_belong_city_dialog_style);
            mListener = listener;
            mDismissListener = dismissListener;
        }

        public void setmListener(PickAndCameraListener listener) {
            this.mListener = listener;
        }

        public void setmDismissListener(MyTrueDismissListener dismissListener) {
            this.mDismissListener = dismissListener;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.upload_personal_head_picture);
            setDialogLayout();
            initViewHeadPictureDialog();
            initDialogListener();
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();
            if (mDismissListener != null) {
                mDismissListener.onDismiss(this);
            }
        }

        private void initViewHeadPictureDialog() {
            head_picture_from_album = (LinearLayout) findViewById(R.id.head_picture_from_album);
            head_picture_from_take_photo = (LinearLayout) findViewById(R.id.head_picture_from_take_photo);
            cancle_upload_head_picture = (FrameLayout) findViewById(R.id.cancle_upload_head_picture);
        }

        private void initDialogListener() {
            //从相册中选照片
            head_picture_from_album.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.selectPhotoFromGallery();
                    } else if (BasePhotoActivity.this instanceof PickAndCameraListener) {
                        ((PickAndCameraListener) BasePhotoActivity.this).selectPhotoFromGallery();
                    }
                    dismiss();

                }
            });
            //拍照
            head_picture_from_take_photo.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onClickTakePhoto();
                    } else if (BasePhotoActivity.this instanceof PickAndCameraListener) {
                        ((PickAndCameraListener) BasePhotoActivity.this).onClickTakePhoto();
                    }

                    dismiss();
                }
            });
            //取消
            cancle_upload_head_picture.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dismiss();
                    if (mDismissListener != null) {
                        mDismissListener.onDismiss(PickAndCameraPhotoDialog.this);
                    }
                }
            });
        }

        private void setDialogLayout() {
            Window window = this.getWindow();
            // 设置显示动画
            window.setWindowAnimations(R.style.popwin_anim_style);
            WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
            windowLayoutParams.width = getWindowManager().getDefaultDisplay().getWidth();
            windowLayoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            window.setAttributes(windowLayoutParams);
            window.setGravity(Gravity.BOTTOM);
        }
    }

    /**
     * 真正点击返回按钮或者取消按钮的取消回调事件。
     */
    public interface MyTrueDismissListener {
        public void onDismiss(DialogInterface dialog);
    }
}
